package dao

import (
	"context"
	"gin_mall/model"

	"gorm.io/gorm"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{NewDBClient(ctx)}
}

func NewUserDaoByDB(db *gorm.DB) *UserDao {
	return &UserDao{db}
}

// 根据用户名判断数据库是否存在该用户，有则返回
func (dao *UserDao) ExisUser(userName, email string) (user *model.User, exist bool) {
	err := dao.DB.Model(&model.User{}).Where("user_name = ? or email = ?", userName, email).First(&user).Error
	if err != nil {
		return nil, false
	}
	return user, true
}

// 判断该邮箱是否存在
func (dao *UserDao) ExistOrNotByEmail(email string) (user *model.User, exist bool) {
	err := dao.DB.Model(&model.User{}).Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, false
	}
	return user, true
}

// 创建用户
func (dao *UserDao) CreateUser(user *model.User) (err error) {
	err = dao.DB.Save(user).Error
	return
}

// 根据 id 获取用户
func (dao *UserDao) GetUserById(uId uint) (user *model.User, err error) {
	err = dao.DB.Model(&model.User{}).Where("id=?", uId).
		First(&user).Error
	return
}

// 更新用户信息
func (dao *UserDao) UpdateUser(user *model.User) error {
	return dao.DB.Model(user).Save(&user).Error
}
